﻿using System;
using System.Collections.Generic;
using System.Linq;
using Missbot.AIModule.Base;
using Missbot.AIModule.Schedulers;
using Missbot.Common;
using Missbot.Core.Base;

namespace Missbot.AIModule
{
    /// <summary>
    /// AI模块管理器
    /// </summary>
    public class AIModuleMgr : ISingleton
    {
        public ILogSvc LogSvc { get; set; }

        /// <summary>
        /// 所有模块列表
        /// </summary>
        public List<IAIModule>  AllModules { get; set; } = new();
        /// <summary>
        /// 所有定时器
        /// </summary>
        public List<IScheduler> Schedulers { get; set; }

        private InstanceConfig InstanceConfig => Configger<AIConfigBase>.AIConfig.Instance;

        public void InitModules()
        {
            AllModules = AutofacSvc.LoadAllInstanceFromClass<IAIModule>()
                                   .OrderByDescending(module => (int) module.Priority)
                                   .ToList();
            foreach (var module in AllModules)
            {
                module.Initialization();
            }
        }

        public void InitSchedules()
        {
            Schedulers = AutofacSvc.LoadAllInstanceFromClass<IScheduler>();
            foreach (var scheduler in Schedulers.Where(sch => sch.Enabled && sch.Owner == InstanceConfig.BotUserName))
            {
                scheduler.Work();
            }
        }
        
        /// <summary>
        /// 接收消息事件
        /// </summary>
        /// <param name="session"></param>
        public void OnInbox(InboxSession session)
        {
            try
            {
                if (AllModules.Any(module => module.OnInbox(session)))
                {
                }
            }
            catch (Exception e)
            {
                LogSvc.LogError(e, session);
            }
        }
    }
}